package cn.iocoder.yudao.module.trade.order.service.calculator;

import cn.iocoder.yudao.module.api.infrastructure.config.dto.MemberConfigRespDTO;
import cn.iocoder.yudao.module.trade.order.bo.TradePriceCalculateReqBO;
import cn.iocoder.yudao.module.trade.order.bo.TradePriceCalculateRespBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.filterList;

/**
 * 赠送积分的 {@link TradePriceCalculator} 实现类
 *
 * @author owen
 */
@Component
@Order(TradePriceCalculator.ORDER_POINT_GIVE)
@Slf4j
public class TradePointGiveCalculator implements TradePriceCalculator {

    @Override
    public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
        // 1.1 校验积分功能是否开启
        MemberConfigRespDTO config = result.getMemberConfig();
        if (config == null) {
            log.debug("[calculate][未获取到用户中心配置，积分赠送不生效]");
            return;
        }
        int giveUnitPoint = config.getPointTradeGiveUnitPoint();
        if (giveUnitPoint <= 0) {
            log.debug("[calculate][积分赠送功能未开启或设置赠送的积分数无效]");
            return;
        }
        // 1.2 校验支付金额
        if (result.getPrice().getPayPrice() <= 0) {
            log.debug("[calculate][未实际支付金额，不赠送积分]");
            return;
        }

        // 2.1 计算赠送积分
        int givePoint = result.getPrice().getPayPrice() / giveUnitPoint;
        if (givePoint == 0) {
            log.warn("[calculate][赠送积分计算为0] payPrice={}, giveUnitPoint={}", result.getPrice().getPayPrice(), giveUnitPoint);
            return;
        }
        // 2.2 计算分摊的赠送积分
        List<TradePriceCalculateRespBO.OrderItem> orderItems = filterList(result.getItems(), TradePriceCalculateRespBO.OrderItem::getSelected);
        List<Integer> dividePoints = TradePriceCalculatorHelper.dividePrice(orderItems, givePoint);

        // 3.2 更新 SKU 赠送积分
        for (int i = 0, n = orderItems.size(); i < n; i++) {
            TradePriceCalculateRespBO.OrderItem orderItem = orderItems.get(i);
            // 产品可能赠送了积分，所以这里要加上
            orderItem.setGivePoint(orderItem.getGivePoint() + dividePoints.get(i));
        }
        // 3.3 更新订单赠送积分
        TradePriceCalculatorHelper.recountAllGivePoint(result);
        log.debug("[calculate][积分赠送计算完成] {}", result.getPrice());
    }

}
